package com.itcode.service.impl;

import com.itcode.exception.AddCategoryNotAllowedException;
import com.itcode.exception.DeletionNotAllowedException;
import com.itcode.exception.GlobalExceptionHandler;
import com.itcode.mapper.CategoryMapper;
import com.itcode.pojo.Category;
import com.itcode.service.CategoryService;
import com.itcode.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    /**
     * 新增分类
     * @param category 文章种类
     */
    @Override
    public void add(Category category) {
        final Map<String, Object> map = ThreadLocalUtil.get();
        final Integer id = (Integer) map.get("id");
        // 查询需要插入的分类是否已经存在，这里根据分类名称进行确定
        Integer categoryNums = categoryMapper.countByName(category.getCategoryName(),id);
        //如果存在，直接返回异常
        if (categoryNums > 0){
            log.error("该分类记录已经存在，无需插入");
            throw new AddCategoryNotAllowedException("该分类记录已经存在，无需插入");
        }

        //不存在，则插入数据
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());


        category.setCreateUser(id);
        categoryMapper.add(category);
    }

    /**
     * 根据id找文章分类
     * @param id id
     * @return 文章分类
     */
    @Override
    public Category findById(Integer id) {
        Category category = categoryMapper.findById(id);
        return category;
    }

    /**
     * 更新分类
     * @param category 分类
     */
    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    /**
     * 删除
     * @param id 分类id
     */
    @Override
    public void remove(Integer id) {
        //1. 判断该类下是否有文章
        //级联查表
        Integer number = categoryMapper.countArticleById(id);

        //2.如果该分类下有文章，则抛出异常
        if (number != null && number > 0){
            throw new DeletionNotAllowedException("该类下有文章，无法删除");
        }

        // 如果没有文章，顺利删除即可
        categoryMapper.deleteById(id);
    }


    public List<Category> findAll() {
        //需要注意，只有创建者才能看到自己的文章分类
        //获取当前用户id
        final Map<String, Object> map = ThreadLocalUtil.get();
        final Integer id = (Integer) map.get("id");
        List<Category> categories = categoryMapper.findAll(id);
        return categories;
    }
}
